package com.tony.dbutil.ibatis.support;

import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.engine.impl.ExtendedSqlMapClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcOperations;


import javax.annotation.PostConstruct;
import java.util.List;

/**
 * Created by Administrator on 2017/1/23.
 */
@SuppressWarnings("unchecked")
public abstract class IbatisBaseDaoSupport<T> extends SqlMapClientDaoSupport implements IbatisBaseDao<T>{

    @Autowired
    private JdbcOperations jdbcOperations;


    @Autowired
    private SqlMapClient sqlMapClient;

//	@Resource(name = "sqlMapClient")
//	public void setSuperSqlMapClient(SqlMapClient sqlMapClient) {
//		super.setSqlMapClient(sqlMapClient);
//	}

    @PostConstruct
    public void initialize() throws Exception {
        super.setSqlMapClient(sqlMapClient);
        if (this.sqlExecutor != null) {
            SqlMapClient sqlMapClient = getSqlMapClientTemplate()
                    .getSqlMapClient();

 /*           ReflectionUtils.setFieldValue(
                    ((ExtendedSqlMapClient) sqlMapClient).getDelegate(),
                    "sqlExecutor", SQLExecutor.class, this.sqlExecutor);*/
        }
    }

    public Object insert(String statementName, Object parameterObject)
            throws DataAccessException {
        return getSqlMapClientTemplate().insert(statementName, parameterObject);
    }

    public int update(String statementName, Object parameterObject)
            throws DataAccessException {
        return getSqlMapClientTemplate().update(statementName, parameterObject);
    }

    public int delete(String statementName, Object parameterObject)
            throws DataAccessException {
        return getSqlMapClientTemplate().delete(statementName, parameterObject);
    }

    public T queryForObject(String statementName, Object parameterObject) {
        return (T) getSqlMapClientTemplate().queryForObject(statementName,
                parameterObject);
    }

    public List<T> queryForList(String statementName, Object parameterObject) {
        return getSqlMapClientTemplate().queryForList(statementName,
                parameterObject);
    }

    private Integer getRowCount(String statementName, Object parameterObject) {
        SQL d = new SQL((ExtendedSqlMapClient) getSqlMapClient(),
                statementName, parameterObject);
        Dialect dialect = null;
        try {
            dialect = this.sqlExecutor.getCurrentDialect(getDataSource().getConnection());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        String sql = dialect.getPageCountString(d.getSql());
        Object[] parameters = d.getParameters();
        return this.jdbcOperations.queryForInt(sql, parameters);
    }


